package com.yuxi.Service.Impl;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import javax.websocket.EncodeException;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.yuxi.Config.ConfigStatic;
import com.yuxi.Dao.CommentRecordDao;
import com.yuxi.Dao.EvaluationRecordBrowseDao;
import com.yuxi.Dao.EvaluationRecordDao;
import com.yuxi.Dao.IExcelDao;
import com.yuxi.Dao.InfoChangeRecordDao;
import com.yuxi.Dao.InformationDao;
import com.yuxi.Dao.InformationFlowDao;
import com.yuxi.Dao.PowerUserDao;
import com.yuxi.Dao.PrisonRoleDao;
import com.yuxi.Dao.PrisonStructureDao;
import com.yuxi.Dao.TaskDispatchDao;
import com.yuxi.Entity.CommentRecord;
import com.yuxi.Entity.EvaluationRecord;
import com.yuxi.Entity.EvaluationRecordBrowse;
import com.yuxi.Entity.FirstCheckExcel;
import com.yuxi.Entity.InforChangeRecord;
import com.yuxi.Entity.Information;
import com.yuxi.Entity.InformationFlow;
import com.yuxi.Entity.InformationOperationRecord;
import com.yuxi.Entity.PowerUser;
import com.yuxi.Entity.PrisonRole;
import com.yuxi.Entity.PrisonStructure;
import com.yuxi.Entity.TaskDispatch;
import com.yuxi.Entity.UserInfo;
import com.yuxi.Entity.UserTaskCompletion;
import com.yuxi.Request.InformationQuery;
import com.yuxi.Request.Page;
import com.yuxi.Service.InformationFlowService;
import com.yuxi.Service.InformationService;
import com.yuxi.Service.UserDoRecordService;
import com.yuxi.Service.UserInformationService;
import com.yuxi.Service.UserService;
import com.yuxi.Service.UserSubService;
import com.yuxi.Util.StringManageUtil;
@Service
public class UserInformationServiceImpl implements UserInformationService {
	@Autowired
	private InformationDao informationDao;
	@Autowired
	private InformationFlowService informationFlowService;
	@Autowired
	private InformationFlowDao informationFlowDao;	
	@Autowired
	private UserDoRecordService userDoRecordService;
	@Autowired
	private CommentRecordDao commentRecordDao;
	@Autowired
	private InfoChangeRecordDao  infoChangeRecordDao;
	@Autowired
	private EvaluationRecordDao evaluationRecordDao;
	@Autowired
	private TaskDispatchDao taskDispatchDao;
	@Autowired
	private UserService userService;
	@Autowired
	private UserSubService userSubService;
	@Autowired
	private EvaluationRecordBrowseDao evaluationRecordBrowseDao;
	@Autowired
	private IExcelDao excelDao;

	private Gson gson=new Gson();
	private Logger logger=LoggerFactory.getLogger(UserInformationServiceImpl.class);
	private StringManageUtil stringManageUtil=new StringManageUtil();
	@Override
	public boolean userAddInformation(Information information, UserInfo user,String ip) {
		try{
			information.setUserId(user.getUserId());
			information.setFlowId(Integer.toString(ConfigStatic.FLOWTABLE.get("InfoManage")));
			information.setFlowName("信息管理");
			information.setCreateTime(System.currentTimeMillis());
			information.setSafetyPortId(information.getSafetyPortId());
			information.setInformationSourceID(","+information.getInformationSourceID()+",");				
			information.setInformationAccount(user.getUserId()+Long.toString(System.currentTimeMillis()));			
			information.setInputPersonID(","+information.getInputPersonID()+",");
			information.setInputPerSonNames(","+information.getInputPerSonNames()+",");
			information.setInformationSourceNames(stringManageUtil.removeDot(information.getInformationSourceNames()));
			information=informationDao.addInformation(information);				
			userDoRecordService.createUserDoRecord(information.getId(), user.getUserId(), ip, ConfigStatic.DOTYPETABLE.get("InformationAdd"), "添加信息",user.getUserName());					
			InformationFlow inFlow=new InformationFlow(System.currentTimeMillis(),System.currentTimeMillis(), true, ConfigStatic.FLOWTABLE.get("InputInfo"), false,information.getId(),0,user.getUserId());
			informationFlowDao.addFlow(inFlow);
			informationFlowService.createInformationFlow(ConfigStatic.FLOWTABLE.get("InfoManage"), information.getId(),user.getUserId(),"添加信息",user.getUserName(),"添加");
			logger.info("用户:"+user.getUserAccount()+"添加信息成功");
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.info("用户:"+user.getUserAccount()+"添加信息失败");
			return false;
		}
	}

	@Override
	public boolean userUpdataInformation(Information information, UserInfo userInfo,String ip) {
		try{
			informationDao.modifyInformation(information);			
			userDoRecordService.createUserDoRecord(information.getId(), userInfo.getUserId(), ip, ConfigStatic.DOTYPETABLE.get("InformationUpDate"), "修改信息",userInfo.getUserName());						
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean userDelInformationById(Information information, UserInfo u,String ip) {
		try{			
			informationDao.deleteInformation(information);			
			userDoRecordService.createUserDoRecord(information.getId(), u.getUserId(), ip, ConfigStatic.DOTYPETABLE.get("InformationDel") , "删除信息",u.getUserName());						
			return true;
		}catch(Exception e){		
			return false;
		}
	}

	@Override
	public Page<Information> userGetInformationList(InformationQuery inforQuery,UserInfo user,String ip,Page<Information> p) {
		try{
			Page<Information> rsp=informationDao.getInfomationByUserId(inforQuery,p, user.getUserId());
			if(rsp==null){
				logger.error(user.getUserAccount()+": 获取已提交的信息列表失败");
				return null;
			}
			logger.info(user.getUserAccount()+": 获取已提交的信息列表成功");
			return rsp;
		}catch(Exception e){
			logger.error(user.getUserAccount()+": 获取已提交的信息列表失败");
			return null;
		}
	}
	
	

	

	
	
	@Override
	public boolean commentInfo(int informationId, String text,String qualityLvId, String taskLvId,String qualityLvName,String taskLvName,String completeText , UserInfo u, String ip) {
		try{
			CommentRecord cRecord =commentRecordDao.getCommentRecordByInfoId(informationId);
			if (cRecord==null) {
				if (taskLvId.equals("0")) {
					cRecord=new CommentRecord(informationId, u.getUserName(), u.getUserId(), text, qualityLvId,  System.currentTimeMillis(), true, qualityLvName);
					
				}else{
					cRecord=new CommentRecord(informationId, u.getUserName(), u.getUserId(), text, qualityLvId, taskLvId, System.currentTimeMillis(), true, qualityLvName, taskLvName,completeText);
					userSubService.subToInfoEvaluation(informationId, u, ip);
				}
				commentRecordDao.addRecord(cRecord);
			}else{
				cRecord.setCreateTime(System.currentTimeMillis());
				cRecord.setInformationQualityId(qualityLvId);
				cRecord.setTaskCompletionId(taskLvId);
				cRecord.setInformationQualityName(qualityLvName);
				cRecord.setTaskCompletionName(taskLvName);
				cRecord.setUserID(u.getUserId());
				cRecord.setUserName(u.getUserName());
				commentRecordDao.modifly(cRecord);
				userSubService.subToInfoEvaluation(informationId, u, ip);
			}
//			CommentRecord cRecord=new CommentRecord(informationId,u.getUserName(),u.getUserId(),text, qualityLvId, taskLvId, System.currentTimeMillis(), true);
			
			logger.info("用户ID："+u.getUserId()+ " 点评信息成功");
			
			
			return true;
		}catch(Exception e){
			logger.info("用户ID："+u.getUserId()+ " 点评信息失败");
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean ratedInfo(int informationId, String text, UserInfo u, String ip,String peopleId,String peopleName) {
		try{
			EvaluationRecord  eRecord=new EvaluationRecord(informationId, text, u.getUserId(),u.getUserName(),System.currentTimeMillis(), true);
			eRecord=evaluationRecordDao.addRecord(eRecord);
			String[] pId=peopleId.split(",");
			String[] pName=peopleName.split(",");
			for (int i = 0; i < pId.length; i++) {
				EvaluationRecordBrowse eRecordBrowse =new EvaluationRecordBrowse(informationId,Integer.valueOf(pId[i]), pName[i], System.currentTimeMillis(),false,eRecord.getId());
				evaluationRecordBrowseDao.addRBrowse(eRecordBrowse);
			}
			logger.info("用户ID："+u.getUserId()+ "评价信息成功");
			return true;
		}catch(Exception e){
			logger.info("用户ID："+u.getUserId()+ "评价信息失败");
			return false;
		}
	}

	@Override
	public Information userGetInformationById(int informationId) {		
		return informationDao.getInformationById(informationId);
	}	
	@Override
	public List<FirstCheckExcel> getInfotmationByIdArray(int[] idArray) {
		if(idArray.length>0){
			return informationDao.getIinformationById(idArray);
		}		
		return null;
	}
	
	@Override
	public boolean prisonAreaToPrison(Integer infoId, UserInfo u) {
		Information info=informationDao.getInformationById(infoId);
		info.setUserId(u.getUserId());
		info.setFlowId(Integer.toString(ConfigStatic.FLOWTABLE.get("InfoManage")));
		info.setFlowName("信息管理");
		info.setCreateTime(System.currentTimeMillis());
		//info.setPrisonId(Integer.toString(p.getId()));
		return false;
	}

	@Override
	public boolean prisonToPrisonArea(Integer infoId, UserInfo u) {
		// TODO Auto-generated method stub
		return false;
	};
	@Override
	public boolean inputTaskFinsh(int informationId,int taskId, String text, UserInfo u, String ip) {
		try{
			Information i= informationDao.getInformationById(informationId);
			String str=i.getTaskCompletion();
			List<UserTaskCompletion> list=gson.fromJson(str, new TypeToken<List<UserTaskCompletion>>(){}.getType());
			UserTaskCompletion taskCompletion=new UserTaskCompletion();
			taskCompletion.setText(text);
			taskCompletion.setUserId(u.getUserId());
			taskCompletion.setAccount(u.getUserAccount());
			taskCompletion.setName(u.getUserName());
			taskCompletion.setTime(Long.toString(System.currentTimeMillis()));			
			if(list==null){
				list=new ArrayList<UserTaskCompletion>();
			}
			list.add(taskCompletion);
			i.setTaskCompletion(gson.toJson(list));
			informationDao.modifyInformation(i);
			TaskDispatch t=taskDispatchDao.getDispatch(taskId);
			t.setEndTime(System.currentTimeMillis());
			t.setStatus(1);
			t.setTaskCompletion(text);
			taskDispatchDao.modifly(t);
			logger.info("用户ID："+u.getUserId()+ " 录入任务完成情况成功");
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.info("用户ID："+u.getUserId()+ " 录入任务完成情况失败");
			return false;
		}
	}
	@Override
	public Information userInfoTogether(String[] infoIdList, int templetId, UserInfo u, String ip) {
		try{
			
			StringBuilder mesure=new StringBuilder("");
			StringBuilder infofile=new StringBuilder("");
			StringBuilder infocont=new StringBuilder("");
			Information templetInfo=informationDao.getInformationById(templetId);		
			for(int i=0;i<infoIdList.length;i++){	
				Information cur=informationDao.getInformationById(Integer.parseInt(infoIdList[i]));			
				mesure.append(cur.getMesure());
				infocont.append(cur.getInformationConternt());
				infofile.append(cur.getInformationProfile());
				userSubService.firstCheckFinshInfoById(Integer.parseInt(infoIdList[i]), u,"初审合并信息", ip);			
			}	
			Information templetInfonew=new Information();
			templetInfonew.setInformationProfile(infofile.toString());
			templetInfonew.setInformationConternt(infocont.toString());
			templetInfonew.setMesure(mesure.toString());	
			templetInfonew.setSafetyPortId(templetInfo.getSafetyPortId());
			templetInfonew.setSafetyPortNames(templetInfo.getSafetyPortNames());
			templetInfonew.setInformationClassificationId(templetInfo.getInformationClassificationId());
			templetInfonew.setInformationClassificationNames(templetInfo.getInformationClassificationNames());
			templetInfonew.setInformationSourceID(templetInfo.getInformationSourceID());
			templetInfonew.setInformationSourceNames(templetInfo.getInformationSourceNames());
			templetInfonew.setInputPersonID(templetInfo.getInputPersonID());
			templetInfonew.setInputPerSonNames(templetInfo.getInputPerSonNames());
			templetInfonew.setInformationSortId(templetInfo.getInformationSortId());
			templetInfonew.setInformationSortNames(templetInfo.getInformationSortNames());
			templetInfonew.setPrisonId(templetInfo.getPrisonId());
			templetInfonew.setPrisonName(templetInfo.getPrisonName());
			templetInfonew.setAppendix(templetInfo.getAppendix());
			Information newInfo=userAddInformationTO(templetInfonew, u, ip);
			return newInfo;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	private Information userAddInformationTO(Information informationTem, UserInfo user,String ip) {
		try{
			informationTem.setUserId(user.getUserId());
			informationTem.setFlowId(Integer.toString(ConfigStatic.FLOWTABLE.get("InfoManage")));
			informationTem.setFlowName("信息管理");
		
			informationTem.setCreateTime(System.currentTimeMillis());			
					
			informationTem.setInformationAccount(user.getUserId()+Long.toString(System.currentTimeMillis()));	
				
			Information  information=informationDao.addInformation(informationTem);	
			userDoRecordService.createUserDoRecord(information.getId(), user.getUserId(), ip, ConfigStatic.DOTYPETABLE.get("InformationAdd"), "添加信息",user.getUserName());					
			InformationFlow inFlow=new InformationFlow(System.currentTimeMillis(),System.currentTimeMillis(), true, ConfigStatic.FLOWTABLE.get("InputInfo"), false,information.getId(),0,user.getUserId());
			informationFlowDao.addFlow(inFlow);
			informationFlowService.createInformationFlow(ConfigStatic.FLOWTABLE.get("InfoManage"), information.getId(),user.getUserId(),"添加信息",user.getUserName(),"添加");			
			return information;
		}catch(Exception e){
			e.printStackTrace();		
			return null;
		}
	}
	
	@Override
	public boolean inforChangeTOPrison(Integer infoId, PrisonStructure targetStruct, UserInfo u, String ip,String remark) {
		try{
			if(!targetStruct.getValue().equals("Prison")){
				return false;
			}
			Information infor=informationDao.getInformationById(infoId);
			String pId=infor.getPrisonId();
			String pName=infor.getPrisonName();		
			infor.setPrisonId(Integer.toString(targetStruct.getId()));
			infor.setPrisonName(targetStruct.getName());
			infor.setFlowId(Integer.toString(ConfigStatic.FLOWTABLE.get("FirstCheck")));
			infor.setFlowName("信息初审");
			infor.setInformationType(ConfigStatic.INFOTYPE.get("prison"));		
			informationFlowService.createInformationFlow(Integer.parseInt(infor.getFlowId()), infoId, u.getUserId(), remark, u.getUserName(),"提交", Integer.parseInt(pId), pName);
			userDoRecordService.createUserDoRecord(infoId, u.getUserId(), ip,ConfigStatic.DOTYPETABLE.get("InformationChangeToPrison"), "从"+pName+"提交到"+targetStruct.getName()+"成功",u.getUserName());
			informationDao.modifyInformation(infor);
			logger.info("信息提交到监狱成功");
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("信息提交到监狱失败");
			return false;
		}
	}
	@Override
	public boolean inforChangeTOPrisonArea(Integer infoId, PrisonStructure targetStruct, UserInfo u, String ip,String remark) {
		try{
			if(!targetStruct.getValue().equals("PrisonArea")){
				return false;
			}
			Information infor=informationDao.getInformationById(infoId);
			String PId=infor.getPrisonId();
			String pName=infor.getPrisonName();
			InforChangeRecord record=infoChangeRecordDao.getNearlyRecordByInfoId(infoId);
			
			if(record!=null&&targetStruct.getId()==record.getSourceId()){
				infor.setPrisonId(Integer.toString(record.getSourceId()));
				infor.setPrisonName(record.getSourceName());
				infor.setFlowId(Integer.toString(record.getSourceFlowId()));
				infor.setFlowName(record.getSourceFlowName());
			}else{
				infor.setPrisonId(Integer.toString(targetStruct.getId()));
				infor.setPrisonName(targetStruct.getName());
				infor.setFlowId(Integer.toString(ConfigStatic.FLOWTABLE.get("FirstCheck")));
				infor.setFlowName("信息初审");
			}			
			infor.setInformationType(ConfigStatic.INFOTYPE.get("prisonArea"));	
			
			informationFlowService.createInformationFlow(Integer.parseInt(infor.getFlowId()), infoId, u.getUserId(), remark, u.getUserName(),"提交", Integer.parseInt(PId), pName);
			informationDao.modifyInformation(infor);			
			userDoRecordService.createUserDoRecord(infoId, u.getUserId(), ip,ConfigStatic.DOTYPETABLE.get("InformationChangeToPrisonArea"), "从"+pName+"提交到"+targetStruct.getName()+"成功",u.getUserName());
			logger.info("信息提交到监区成功");
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("信息提交到监区失败");			
			return false;
		}
	}

	@Override
	public void delInfoById(Integer id) {
		informationDao.deleteInformationBYId(id);		
	}

	@Override
	public void delOwnExporId(Integer id) {
		excelDao.deleteOwnById(id);
	}

}
